﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Media;
using System.Runtime.Serialization.Formatters.Binary;
using System.Speech.Synthesis;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using Fluent;
using LSA.Framework;
using System.Linq;
using System.Windows.Media.Imaging;
using LSA.OnlineResources;

namespace Visuals
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow2 : RibbonWindow
    {
        public static MainWindow2 Object = null;
        public LsaSpace lsaSpace;
        private int totalSelectedWords = 0;
        private int totalSelectedDocuments = 0;
        private bool wordsGrouped = false;
        private KeyValuePair<string, int> wordsListContextMenu;
        private KeyValuePair<string, int> centerWordGraph;
        public string[] fileNames;
        public Dictionary<string, byte> Entities;
        private bool showOnlyEntities = false;

        public MainWindow2()
        {
            InitializeComponent();
            LoadStopWordsSettings();
            if(Object != null)
            {
                App.Current.Shutdown();
                return;
            }
            Object = this;
        }

        private void LoadStopWordsSettings()
        {
            stopWordsList.Items.Clear();
            foreach (string stopWord in Properties.Settings.Default.StopWords)
            {
                stopWordsList.Items.Add(stopWord);
            }
        }

        private void LoadWordsAndDocumentsList()
        {
            wordsList.Items.Clear();
            documentsList.Items.Clear();

            var enumerator = lsaSpace.AllWords;
            while (enumerator.MoveNext())
            {
                try
                {
                    var pair = (KeyValuePair<string, int>)enumerator.Current;
                    wordsList.Items.Add(
                        new KeyValuePair<string, int>(
                            (lsaSpace.IsWordEntity(pair.Value))
                                ? lsaSpace.GetEntityString(pair.Key)
                                : pair.Key, pair.Value));
                } catch (ArgumentOutOfRangeException)
                {
                    
                }
            }

            int i = 0;
            foreach (string fileName in lsaSpace.FileNames)
            {
                documentsList.Items.Add(new DocumentPair { Id = i, File = fileName.Split('\\').Last(), Words = lsaSpace.WordsPerDocument(i++) });
            }
        }

        private void EnableButtons()
        {
            wordToWordButton.IsEnabled = true;
            documentToDocumentButton.IsEnabled = true;
            wordsGroup.IsEnabled = true;
            wordsChartButton.IsEnabled = true;
            wordsGroupsPreview.IsEnabled = true;
            searchButton.IsEnabled = true;
            wordsD1Spinner.Maximum = lsaSpace.Dimension;
            wordsD2Spinner.Maximum = lsaSpace.Dimension;
            wordsClustersSpinner.Maximum = lsaSpace.WordsCount;
            wordsPerClusterSpinner.Maximum = lsaSpace.WordsCount;
            if (lsaSpace.WordsCount > 20)
            {
                wordsClustersSpinner.Value = 5;
                wordsPerClusterSpinner.Value = 20;
            }
        }

        private void SelectGeneralTab()
        {
            generalTab.IsOpen = true;
            generalTab.Visibility = Visibility.Visible;
            generalTab.IsSelected = true;
        }

        public void LoadCorpus()
        {
            loadCorpusButton_Click(this, new RoutedEventArgs());
        }

        public void OpenProject()
        {
            openButton_Click(this, new RoutedEventArgs());
        }
        
        public void BuildCorpus()
        {
            rebuildButton_Click(this, new RoutedEventArgs());
        }

        private async void loadCorpusButton_Click(object sender, RoutedEventArgs e)
        {
            SelectGeneralTab();

            var dialog = new Microsoft.Win32.OpenFileDialog { Multiselect = true, Filter = "Text documents (.txt)|*.txt" };
            var folderResult = dialog.ShowDialog();
            if (folderResult == true)
            {
                try
                {
                    fileNames = dialog.FileNames;
                    numberOfDimensions.Maximum = fileNames.Length;
                    numberOfDimensions.Value = fileNames.Length;
                }
                catch (ArgumentException exception)
                {
                    MessageBox.Show(exception.Message, "Грешка при зареждане на корпус!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void wordToWordButton_Click(object sender, RoutedEventArgs e)
        {
            if (lsaSpace == null)
            {
                MessageBox.Show("Първо трябва да заредите корпус.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (wordsList.SelectedItems.Count != 2)
            {
                MessageBox.Show("Трябва да изберете точно две думи.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var word1 = (KeyValuePair<string, int>)wordsList.SelectedItems[0];
            var word2 = (KeyValuePair<string, int>)wordsList.SelectedItems[1];
            MessageBox.Show("Връзката между '" + word1.Key + "' и '" + word2.Key + "' е " + lsaSpace.RelationBetweenWords(word1.Value, word2.Value).ToString(), "Връзка", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void documentToDocumentButton_Click(object sender, RoutedEventArgs e)
        {
            if (lsaSpace == null)
            {
                MessageBox.Show("Първо трябва да заредите корпус.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (documentsList.SelectedItems.Count != 2)
            {
                MessageBox.Show("Трябва да изберете точно два документа.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var document1 = (DocumentPair)documentsList.SelectedItems[0];
            var document2 = (DocumentPair)documentsList.SelectedItems[1];
            MessageBox.Show("Връзката между '" + document1.File + "' и '" + document2.File + "' е " + lsaSpace.RelationBetweenWords(document1.Id, document2.Id).ToString(), "Връзка", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private void wordsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            totalSelectedWords += (e.AddedItems.Count - e.RemovedItems.Count);
            if (totalSelectedWords > 0)
            {
                wordInfo.Visibility = Visibility.Visible;
                try
                {
                    wordInfo.Header = (totalSelectedWords == 1) ? ((KeyValuePair<string, int>)e.AddedItems[0]).Key : "Multiple";
                }
                catch
                {
                    wordInfo.Header = "Дума ...";
                }
            }
            else
            {
                wordInfo.Visibility = Visibility.Collapsed;
            }
        }

        private void documentsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            totalSelectedDocuments += (e.AddedItems.Count - e.RemovedItems.Count);
            if (totalSelectedDocuments > 0)
            {
                documentInfo.Visibility = Visibility.Visible;
                try
                {
                    documentInfo.Header = (totalSelectedDocuments == 1) ? ((DocumentPair)e.AddedItems[0]).File : "Multiple";
                }
                catch
                {
                    documentInfo.Header = "Документ ...";
                }
            }
            else
            {
                documentInfo.Visibility = Visibility.Collapsed;
            }
        }

        private void documentsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("NotImplementedException");
        }

        private bool FilterWordsList(object obj)
        {
            if (obj == null) return false;

            string textFilter = SearchBox.Text;

            if (textFilter.Trim().Length == 0) return true;
            var word = (KeyValuePair<string, int>)obj;

            if (word.Key.ToLower().Contains(textFilter.ToLower()) || wordsList.SelectedItems.Contains(obj)) return true;
            return false;
        }

        private void SearchBox_Update(object sender, EventArgs e)
        {
            ICollectionView view = CollectionViewSource.GetDefaultView(wordsList.Items);
            view.Filter = new Predicate<object>(FilterWordsList);
        }

        private async void wordsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DependencyObject obj = (DependencyObject)e.OriginalSource;

            while (obj != null && obj != wordsList)
            {
                if (obj.GetType() == typeof(ListViewItem))
                {
                    var listItem = (ListViewItem)obj;
                    var content = (KeyValuePair<string, int>)listItem.Content;
                    DrawZeroWord(content);
                    
                    ISearchEngine engine = new BingSearch(content.Key);
                    List<SearchResult> results = new List<SearchResult>();
                    
                    await TaskEx.Run(delegate() {
                        lock (this)
                        {
                            try
                            {
                                results = engine.Search();
                            }
                            catch(System.Net.WebException)
                            {
                                MessageBox.Show("Проблем с връзката с интернет!");
                            }
                        }
                    });
                    
                    searchResultsList.Items.Clear();
                    foreach (SearchResult result in results)
                    {
                        searchResultsList.Items.Add(new {Title = result.Title, Content = result.Content});
                    }

                    break;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }

        }

        private void DrawZeroWord(KeyValuePair<string, int> word)
        {
            centerWordGraph = word;
            double distance = Math.Min(drawGrid.Height, drawGrid.Width);
            distance = (distance / 2);

            int count = (int)numberOfGraphicNodes.Value;
            double centerX = (drawGrid.Width / (double)2) - 50;
            double centerY = (drawGrid.Height / (double)2) - 11;
            drawGrid.Children.Clear();

            var centerWord = BuildLabel(word.Key);
            centerWord.FontSize = 15;
            centerWord.Background = Brushes.Indigo;
            centerWord.Foreground = Brushes.White;
            centerWord.Padding = new Thickness(1);
            centerWord.SetValue(Canvas.LeftProperty, centerX);
            centerWord.SetValue(Canvas.TopProperty, centerY);
            drawGrid.Children.Add(centerWord);

            int i = 0;
            foreach (WordRelationPair pair in lsaSpace.GetKnnOfWord(word.Value, count, showOnlyEntities))
            {
                var otherWord = BuildLabel(lsaSpace.GetWordString(pair.Index, true));
                otherWord.MouseLeftButtonUp += graphicItem_Click;
                otherWord.MouseEnter += graphicItem_MouseEnter;
                otherWord.MouseLeave += graphicItem_MouseLeave;
                otherWord.MouseRightButtonDown += new MouseButtonEventHandler(graphicItem_MouseRightButtonDown);

                var angle = (Math.PI / (double)180) * (i * (360 / (double)count));
                otherWord.SetValue(Canvas.LeftProperty, centerX - 300 * (Math.Cos(angle)));
                otherWord.SetValue(Canvas.TopProperty, centerY - 120 * Math.Sin(angle));

                if (angle <= Math.PI)
                {
                    var line = new Line()
                                {
                                    X1 = (double)centerWord.GetValue(Canvas.LeftProperty) + 50,
                                    Y1 = (double)centerWord.GetValue(Canvas.TopProperty) + 11,
                                    X2 = (double)otherWord.GetValue(Canvas.LeftProperty) + 45,
                                    Y2 = (double)otherWord.GetValue(Canvas.TopProperty) + 20,
                                };

                    line.SetValue(Canvas.ZIndexProperty, -1);

                    double def = (pair.Relation > 1.0) ? 1.0 : pair.Relation;

                    byte red = (byte)(Math.Abs(def) * 255);
                    SolidColorBrush s = new SolidColorBrush(Color.FromArgb(red, 255, 0, 0));
                    line.StrokeThickness = 3;
                    line.Stroke = s;

                    drawGrid.Children.Add(otherWord);
                    drawGrid.Children.Add(line);
                    i++;
                }
                else
                {
                    var line = new Line()
                    {
                        X1 = (double)centerWord.GetValue(Canvas.LeftProperty) + 50,
                        Y1 = (double)centerWord.GetValue(Canvas.TopProperty) + 11,
                        X2 = (double)otherWord.GetValue(Canvas.LeftProperty) + 45,
                        Y2 = (double)otherWord.GetValue(Canvas.TopProperty) + 5,
                    };
                    line.SetValue(Canvas.ZIndexProperty, -1);
                    double def = (pair.Relation > 1.0) ? 1.0 : pair.Relation;

                    byte red = (byte)(Math.Abs(def) * 255);
                    SolidColorBrush s = new SolidColorBrush(Color.FromArgb(red, 255, 0, 0));
                    line.StrokeThickness = 3;
                    line.Stroke = s;

                    drawGrid.Children.Add(otherWord);
                    drawGrid.Children.Add(line);
                    i++;
                }
            }
        }

        void graphicItem_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Controls.ContextMenu contextMenuWord = new System.Windows.Controls.ContextMenu();
            System.Windows.Controls.MenuItem menuItemFind = new System.Windows.Controls.MenuItem();
            menuItemFind.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/search.png", UriKind.Relative)) };
            menuItemFind.Header = "Виж в свързаните документи";

            menuItemFind.Click += (x, y) => OpenNewSearchPreview((string)((Label)sender).Content);
            contextMenuWord.Items.Add(menuItemFind);
            ((Label)sender).ContextMenu = contextMenuWord;
        }

        private void graphicItem_Click(object sender, EventArgs e)
        {
            string wordName = (string)((Label)sender).Content;
            try
            {
                DrawZeroWord(new KeyValuePair<string, int>(wordName, lsaSpace.GetWordId(wordName, showOnlyEntities)));
            } 
            catch(ArgumentOutOfRangeException)
            {
                MessageBox.Show("В корпуса няма такава дума.");
                return;
            }
        }

        private void graphicItem_MouseEnter(object sender, EventArgs e)
        {
            ((Label)sender).FontSize = 13;
            ((Label)sender).Padding = new Thickness(0);
            ((Label)sender).SetValue(Canvas.ZIndexProperty, 1);
            ((Label)sender).ToolTip = BuildTooltip(((Label)sender).Content.ToString());
        }

        private void graphicItem_MouseLeave(object sender, EventArgs e)
        {
            ((Label)sender).FontSize = 12;
            ((Label)sender).Padding = new Thickness(4);
            ((Label)sender).SetValue(Canvas.ZIndexProperty, 0);

        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            SelectGeneralTab();

            var dialog = new Microsoft.Win32.SaveFileDialog { FileName = "Lsa Space", DefaultExt = ".lsa", Filter = "Lsa Space documents (.lsa)|*.lsa" };
            var folderResult = dialog.ShowDialog();
            if (folderResult == true)
            {
                Stream stream = File.Open(dialog.FileName, FileMode.Create);
                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(stream, lsaSpace);
                stream.Close();

                if (lsaSpace.IsBulgarian)
                {
                    SoundPlayer simpleSound =
                        new SoundPlayer(@"Sounds\corpusSaved.wav");
                    simpleSound.Play();
                }
                else
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.Speak("Operation was successful.");
                    }
                }
            }
        }

        private async void openButton_Click(object sender, RoutedEventArgs e)
        {
            SelectGeneralTab();

            var dialog = new Microsoft.Win32.OpenFileDialog { Multiselect = false, Filter = "Lsa Space documents (.lsa)|*.lsa" };
            var folderResult = dialog.ShowDialog();
            if (folderResult == true)
            {
                await TaskEx.Run(delegate()
                               {
                                   Stream stream = File.Open(dialog.FileName, FileMode.Open);
                                   BinaryFormatter bFormatter = new BinaryFormatter();
                                   lsaSpace = (LsaSpace)bFormatter.Deserialize(stream);
                                   stream.Close();
                               });

                if (!File.Exists(lsaSpace.FileNames[0]))
                {
                    MessageBox.Show("Файловете използвани в корпуса не бяха открити. Ще се опитаме да го възстановим, моля посочете един от файловете.");
                    var dialogFile = new Microsoft.Win32.OpenFileDialog { Multiselect = false, Filter = "Text file (.txt)|*.txt" };
                    var fileResult = dialogFile.ShowDialog();
                    if (fileResult == true)
                    {
                        string oldPath = lsaSpace.FileNames[0].Replace(lsaSpace.FileNames[0].Split('\\').Last(), "");
                        string newPath = dialogFile.FileName.Replace(dialogFile.FileName.Split('\\').Last(), "");

                        for (int i = 0; i < lsaSpace.FileNames.Length; i++)
                        {
                            lsaSpace.FileNames[i] = lsaSpace.FileNames[i].Replace(oldPath, newPath);
                            if (!File.Exists(lsaSpace.FileNames[0]))
                            {
                                MessageBox.Show("Възстановяването не бе успешно. Или сте избрали грешна директория, или някаи файлове липсват. Програмата ще се изключи.");
                                App.Current.Shutdown();
                                return;
                            }
                        }
                    }
                }

                LoadWordsAndDocumentsList();
                EnableButtons();

                if (lsaSpace.Entities.Count > 1)
                {
                    showOnlyEntities = true;
                }

                if (lsaSpace.IsBulgarian)
                {
                    SoundPlayer simpleSound =
                        new SoundPlayer(@"Sounds\corpusLoaded.wav");
                    simpleSound.Play();
                }
                else
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.Speak("Operation was successful.");
                    }
                }
            }
        }

        private void aboutButton_Click(object sender, RoutedEventArgs e)
        {
            SelectGeneralTab();
            var about = new AboutWindow();
            about.ShowDialog();
        }

        private void wordsChartButton_Click(object sender, RoutedEventArgs e)
        {
            if (lsaSpace == null)
            {
                MessageBox.Show("Първо трябва за заредите корпус.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (wordsList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Трябва да изберете поне една дума.", "Грешка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var b = new List<PointPair>();

            foreach (var obj in wordsList.SelectedItems)
            {
                var item = (KeyValuePair<string, int>)obj;
                var coordinates = lsaSpace.Get2dWordCoordinates(item.Value, ((int)wordsD1Spinner.Value) - 1,
                                                                ((int)wordsD2Spinner.Value) - 1);
                b.Add(new PointPair { Description = item.Key, X = coordinates[0], Y = coordinates[1] });
            }

            if (wordsList.SelectedItems.Count == 1)
            {
                var other = lsaSpace.GetKnnOfWord(((KeyValuePair<string, int>) wordsList.SelectedItems[0]).Value,
                                                  (int) numberOfGraphicNodes.Value, showOnlyEntities);
                foreach (WordRelationPair relationPair in other)
                {
                    var coordinates = lsaSpace.Get2dWordCoordinates(relationPair.Index, ((int)wordsD1Spinner.Value) - 1,
                                                                ((int)wordsD2Spinner.Value) - 1);
                    b.Add(new PointPair { Description = lsaSpace.GetWordString(relationPair.Index), X = coordinates[0], Y = coordinates[1] });
                }
            }

            if (wordsAbsCheckbox.IsChecked == true)
            {
                var maxX = b.Max(item => Math.Abs(item.X));
                var maxY = b.Max(item => Math.Abs(item.Y));
                foreach (PointPair pair in b)
                {
                    pair.X = ((pair.X) / Math.Abs(maxX)) * 100;
                    pair.Y = ((pair.Y) / Math.Abs(maxY)) * 100;
                }
            }

            var charWindow = new CoordinateChartWindow(b);
            charWindow.Title = "Координатна система - " + ((wordsAbsCheckbox.IsChecked == true) ? "Относителна" : "Абсолютна") + " (" + wordsD1Spinner.Value + ", " + wordsD2Spinner.Value + ")";
            charWindow.Show();
        }

        private async void wordsGroup_Click(object sender, RoutedEventArgs e)
        {
            if (lsaSpace == null)
            {
                MessageBox.Show("Трябва първо да заредите корпус.");
                return;
            }

            await TaskEx.Run(delegate()
                                 {
                                     Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                                                                                      {
                                                                                          lsaSpace.KMeansClusterWords(
                                                                                              (int)
                                                                                              wordsClustersSpinner.Value);
                                                                                      }));
                                 });

            wordsGrouped = true;
            MessageBox.Show("Групирането завърши успешно.");
        }

        private void wordsGroupsPreview_Click(object sender, RoutedEventArgs e)
        {
            if (!wordsGrouped)
            {
                MessageBox.Show("Трябва първо да групирате думи.");
                return;
            }

            GetStringForWordId deleg = lsaSpace.GetWordString;

            lsaSpace.GetAllWordsClusters((int)wordsPerClusterSpinner.Value);
            var previewWindow = new WordGroupsPreviewWindow(lsaSpace.GetAllWordsClusters((int)wordsPerClusterSpinner.Value), deleg);
            previewWindow.Show();
        }

        private void drawGrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            //drawGrid.Width = 200;
            //drawGrid.Height = 500;
        }

        private void wordsList_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            contextMenu.Visibility = Visibility.Collapsed;

            DependencyObject obj = (DependencyObject)e.OriginalSource;

            while (obj != null && obj != wordsList)
            {
                if (obj.GetType() == typeof(ListViewItem))
                {
                    var listItem = (ListViewItem)obj;
                    wordsListContextMenu = (KeyValuePair<string, int>)listItem.Content;

                    contextMenu.PlacementTarget = sender as UIElement;
                    contextMenu.Visibility = Visibility.Visible;

                    break;
                }
                obj = VisualTreeHelper.GetParent(obj);
            }
        }

        private void wordsList_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            // disables the SelectedIndex code 
            //e.Handled = true; 
        }

        private void wordsListContextMenu_MarkAsEntity(object sender, RoutedEventArgs e)
        {

        }

        private void wordsListContextMenu_AddToStopList(object sender, RoutedEventArgs e)
        {
            var result =
                MessageBox.Show("Сигурен ли сте, че искате да добавите " + wordsListContextMenu.Key + " към Stop words?",
                                "Проверка", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                if (!Properties.Settings.Default.StopWords.Contains(wordsListContextMenu.Key))
                {
                    stopWordsList.Items.Add(wordsListContextMenu.Key);
                    Properties.Settings.Default.StopWords.Add(wordsListContextMenu.Key);
                    Properties.Settings.Default.Save();
                }
            }
        }

        private async void rebuildButton_Click(object sender, RoutedEventArgs e)
        {
            var result = (lsaSpace == null) ? MessageBoxResult.Yes : 
                MessageBox.Show("Сигурен ли си сте, че искате да стартирате изграждане на корпуса?",
                                "Проверка", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                fileNames = (fileNames == null && lsaSpace != null) ? lsaSpace.FileNames : fileNames;
                if (fileNames == null || (fileNames != null && fileNames.Length < 2))
                {
                    MessageBox.Show("Трябва да изберете поне два файла.");
                    return;
                }
                try
                {
                    int dimensions = (int)numberOfDimensions.Value;
                    bool tfidf = useTfIdf.IsChecked == true;
                    bool stem = shouldStem.IsChecked == true;
                    if (lsaSpace != null) Entities = lsaSpace.Entities;

                    await
                    TaskEx.Run(delegate()
                                   {
                                       lsaSpace = new LsaSpace(fileNames, tfidf, stem,
                                                               Properties.Settings.Default.StopWords.Cast<string>().
                                                                   ToArray(), Entities, dimensions);
                                   });
                    LoadWordsAndDocumentsList();
                    EnableButtons();

                    if (lsaSpace.Entities.Count > 1)
                    {
                        showOnlyEntities = true;
                    }

                    if (lsaSpace.IsBulgarian)
                    {
                        SoundPlayer simpleSound =
                            new SoundPlayer(@"Sounds\corpusBuilt.wav");
                        simpleSound.Play();
                    }
                    else
                    {
                        using (SpeechSynthesizer synth = new SpeechSynthesizer())
                        {
                            synth.Speak("Corpus was successfully built.");
                        }
                    }
                }
                catch (ArgumentException exception)
                {
                    MessageBox.Show(exception.Message, "Грешка при зареждането на корпуса", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }
            }
        }

        private void addStopWordButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(stopWordInput.Text) && !stopWordsList.Items.Contains(stopWordInput.Text))
            {
                stopWordsList.Items.Add(stopWordInput.Text);
                Properties.Settings.Default.StopWords.Add(stopWordInput.Text);
                Properties.Settings.Default.Save();
                stopWordInput.Text = "";
            }
        }

        private void removeStopWordButton_Click(object sender, RoutedEventArgs e)
        {
            if (stopWordsList.SelectedItems.Count == 1)
            {
                Properties.Settings.Default.StopWords.Remove(stopWordsList.SelectedItem.ToString());
                Properties.Settings.Default.Save();
                stopWordsList.Items.Remove(stopWordsList.SelectedItem);
            }
        }

        private void OpenNewSearchPreview(string word)
        {
            SearchPreview window = new SearchPreview(lsaSpace);

            if (word != null)
            {
                window.textBoxSearchBox.Text = word;
                window.InitializeSearch();
            }

            window.Show();
        }

        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            OpenNewSearchPreview(null);
        }

        public Label BuildLabel(string content)
        {
            var label = new Label()
            {
                Content = content,
                Height = 22,
                Width = 100,
                Background = Brushes.Transparent,
                Padding = new Thickness(4),
                VerticalAlignment = VerticalAlignment.Center,
                VerticalContentAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                HorizontalContentAlignment = HorizontalAlignment.Center
            };
            return label;
        }
        
        public ToolTip BuildTooltip(string word)
        {
            int wordID;
            try
            {
                wordID = lsaSpace.GetWordId(word, showOnlyEntities);
            } 
            catch (ArgumentOutOfRangeException)
            {
                if (lsaSpace.IsBulgarian)
                {
                    SoundPlayer simpleSound =
                        new SoundPlayer(@"Sounds\wordNotFoundInCorpus.wav");
                    simpleSound.Play();
                }
                else
                {
                    using (SpeechSynthesizer synth = new SpeechSynthesizer())
                    {
                        synth.Speak("Word not found in the corpus.");
                    }
                }
                return null;
            }
            StackPanel stackPanel = new StackPanel();
            TextBlock textBlockWordID = new TextBlock();
            TextBlock textBlockWords = new TextBlock() { Text = "\nДокументи с думата:" };
            TextBlock textRelation = new TextBlock();
            ListBox listBoxDocuments = new ListBox();
            textBlockWordID.Text = String.Format("ID: {0} ", wordID);
            textRelation.Text = String.Format("\nВръзка с главната дума: \n" + lsaSpace.RelationBetweenWords(wordID, centerWordGraph.Value));
            for (int i = 0; i < ((lsaSpace.DocumentsWithWord(wordID).Count > 6) ? 6 : lsaSpace.DocumentsWithWord(wordID).Count); i++)
            {
                listBoxDocuments.Items.Add(lsaSpace.FileNames[lsaSpace.DocumentsWithWord(wordID)[i]].Split('\\').Last());
            }
            if (lsaSpace.DocumentsWithWord(wordID).Count > 6)
                listBoxDocuments.Items.Add("и други...");

            stackPanel.Children.Add(textBlockWordID);
            stackPanel.Children.Add(textBlockWords);
            stackPanel.Children.Add(listBoxDocuments);
            stackPanel.Children.Add(textRelation);

            ToolTip toolTip = new ToolTip()
            {
                Content = stackPanel,
                Background = Brushes.Honeydew,
                Height = 200,
                Width = 200,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            return toolTip;
        }

        private void wordsListContextMenu_ViewSearch(object sender, RoutedEventArgs e)
        {
            OpenNewSearchPreview(wordsListContextMenu.Key);
        }
    }
}

